import Taro from '@tarojs/taro'
import React, { Component } from 'react'
import { View } from '@tarojs/components'
import { AtImagePicker } from 'taro-ui'
import API_BASEURL from '@/services/config/ipconfig'

export type File = Array<{
  file: {
    path: string
    size: number
  }
  uploadUrl: string //上传后返回的地址
  url: string //预览的零时地址
}>

type PageProps = {
  // 如果想自定义ui，需要在组件上传入name='slot'
  name?: 'slot'
  fileList: Array<{
    url: string
  }>
  onHandChange: (data: File) => void
}

class Photograph extends Component<PageProps> {
  // 自定义ui的上传方法
  photograph() {
    const self = this
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0]
        self.uploadFile([{ url: tempFilePaths }])
      }
    })
  }
  // 上传到服务器
  uploadFile = (file) => {
    const len = file.length - 1
    Taro.showLoading({ title: '上传中...' })
    const self = this
    Taro.uploadFile({
      url: `${API_BASEURL.baseUrl}/citizens/ApiV2/Dictionary/uploadImage`,
      filePath: file[len].url,
      name: 'File',
      formData: {
        Type: 'jpeg',
        GuId: 'wx',
        Ftype: 4
      },
      success(res) {
        const data = JSON.parse(res.data).data
        // 上传成功后，后台返回的url加入file数组中，返给父组件
        file[len].uploadUrl = data[0].url
        console.log(file)
        self.props.onHandChange(file)
        Taro.showToast({
          title: '上传成功',
          icon: 'success'
        })
        Taro.hideLoading()
      },
      fail(err) {
        Taro.hideLoading()
        Taro.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  }
  /**
   * @param file
   * @param operationType
   * @description 上传前的操作 add是添加图片，remove是移除图片
   */
  handChangeBefore = (file, operationType: 'add' | 'remove') => {
    console.log(file, operationType)
    if (operationType === 'add') {
      this.uploadFile(file)
    } else if (operationType === 'remove') {
      this.props.onHandChange(file)
    }
  }
  render() {
    const { name, fileList } = this.props
    return (
      // 引入该组件必传onHandChange和fileList
      <View>
        {name === 'slot' ? (
          <View onClick={this.photograph.bind(this)}>{this.props.children}</View>
        ) : (
          <AtImagePicker files={fileList} onChange={this.handChangeBefore}></AtImagePicker>
        )}
      </View>
    )
  }
}

export default Photograph
